<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '申请',
  },
}
</route>

<template>
  <view style="height: 100%; padding: 30rpx" class="">
    <wd-form ref="form" :model="model">
      <wd-cell-group border title="执照信息">
        <wd-cell title="身份证正面" title-width="100px">
          <wd-upload @success="(_event) => onSuccess(_event, 'ID_CARD_FRONT')" :limit="1" :form-data="{
            sourcechnl: 1,
            imgType: 'ID_CARD_FRONT',
          }" v-model:file-list="fileList1" accept="image"
            action="https://ryxkeji.com/api/app/lakala/merchant/file/upload">

            <!-- <image v-if="ID_CARD_FRONT_IMAGE.showUrl"  :src="ID_CARD_FRONT_IMAGE.showUrl" mode="scaleToFill" /> -->
          </wd-upload>
        </wd-cell>

        <wd-cell title="身份证反面" title-width="100px">
          <wd-upload @success="(_event) => onSuccess(_event, 'ID_CARD_BEHIND')" :limit="1" :form-data="{
            sourcechnl: 1,
            imgType: 'ID_CARD_BEHIND',
          }" v-model:file-list="fileList2" accept="image"
            action="https://ryxkeji.com/api/app/lakala/merchant/file/upload">
            <!-- <image v-if="ID_CARD_BEHIND_IMAGE.showUrl" class="h-80 w-full" :src="ID_CARD_BEHIND_IMAGE.showUrl" mode="scaleToFill" /> -->
          </wd-upload>
        </wd-cell>

        <!-- <wd-input
          label="经营者姓名"
          label-width="100px"
          prop="cert_name"
          clearable
          v-model="model.cert_name"
          required
        /> -->
        <wd-input label="法⼈姓名" :rules="[{ required: true, message: '请输入经营者姓名' }]" label-width="100px" prop="larName"
          clearable v-model="model.larName" required />

        <wd-input label="身份证号" :rules="[{ required: true, message: '请输入身份证号' }]" label-width="100px" prop="larIdCard"
          clearable v-model="model.larIdCard" required />

        <wd-datetime-picker type="date" :rules="[{ required: true, message: '请选择身份证开始日期' }]" label="身份证开始日期"
          label-width="100px" prop="larIdCardStart" v-model="model.larIdCardStart" :minDate="0" required />

        <wd-datetime-picker type="date" :rules="[{ required: true, message: '请选择身份证结束日期' }]" label="身份证结束日期"
          label-width="100px" prop="larIdCardEnd" v-model="model.larIdCardEnd" :minDate="0" required
          :maxDate="new Date().getTime() + 36500 * 24 * 60 * 60 * 1000" />
      </wd-cell-group>

      <!-- 商户信息 -->
      <wd-cell-group border title="商户信息">
        <wd-input label="商户经营名称" :rules="[{ required: true, message: '请输入商户经营名称' }]" label-width="100px"
          prop="merRegName" clearable v-model="model.merRegName" required />

        <wd-col-picker label="商户所在地区" :rules="[{ required: true, message: '商户所在地区' }]" v-model="areaValue"
          :columns="area" :column-change="columnChange" @confirm="handleConfirm"></wd-col-picker>

        <wd-input label="详细地址" :rules="[{ required: true, message: '详细地址' }]" label-width="100px" prop="merAddr"
          clearable v-model="model.merAddr" required />
        <!-- email -->
        <wd-input label="邮箱" :rules="[{ required: true, message: '邮箱' }]" label-width="100px" prop="email" clearable
          v-model="model.email" required />
        <wd-input :rules="[{ required: true, message: '手机号' }]" label="签约手机号（必须是本人）" label-width="100px"
          prop="contactMobile" clearable v-model="model.contactMobile" required />
      </wd-cell-group>

      <!-- 结算信息 -->
      <wd-cell-group border title="结算信息">
        <wd-cell title="银行卡照片" title-width="100px">
          <wd-upload @success="(_event) => onSuccess(_event, 'BANK_CARD')" :limit="1" :form-data="{
            sourcechnl: 1,
            imgType: 'BANK_CARD',
          }" v-model:file-list="fileList3" accept="image"
            action="https://ryxkeji.com/api/app/lakala/merchant/file/upload">

            <!-- <image v-if="BANK_CARD_IMAGE.showUrl" class="h-80 w-full" :src="BANK_CARD_IMAGE.showUrl" mode="scaleToFill" /> -->
          </wd-upload>
        </wd-cell>

        <!-- 开户名 -->
        <!-- <wd-input
          label="开户名"
          label-width="100px"
          prop="accountName"
          clearable
          v-model="model.accountName"
          required
        /> -->

        <!-- 卡号 -->
        <wd-input :rules="[{ required: true, message: '请输入银行卡号' }]" label="银行卡号" label-width="100px" prop="accountNo"
          clearable v-model="model.accountNo" required />

        <wd-col-picker :rules="[{ required: true, message: '请选择开户行' }]" label="开户行" v-model="openningBank"
          :columns="bankArea" :column-change="handleOpenningBankColumnChange"
          @confirm="handleOpenningBankConfirm"></wd-col-picker>
      </wd-cell-group>

      <wd-cell-group border title="执照信息">
        <!-- 经营名称，不能少于七个中文 -->
        <wd-input :rules="[{ required: true, message: '请输入商户注册名称' }]" label="商户注册名称" label-width="100px" prop="merName"
          clearable v-model="model.merName" required :rule="[
            { required: true, message: '请输入经营名称', trigger: 'blur' },
            { min: 7, message: '不能少于七个中文', trigger: 'blur' },
          ]" />

        <wd-cell title="门头照" title-width="100px">
          <wd-upload @success="(_event) => onSuccess(_event, 'SHOP_OUTSIDE_IMG')" :limit="1" :form-data="{
            sourcechnl: 1,
            imgType: 'SHOP_OUTSIDE_IMG',
          }" v-model:file-list="fileList4" accept="image"
            action="https://ryxkeji.com/api/app/lakala/merchant/file/upload"></wd-upload>
        </wd-cell>

        <wd-cell title="内设照" title-width="100px">
          <wd-upload @success="(_event) => onSuccess(_event, 'SHOP_INSIDE_IMG')" :limit="1" :form-data="{
            sourcechnl: 1,
            imgType: 'SHOP_INSIDE_IMG',
          }" v-model:file-list="fileList5" accept="image"
            action="https://ryxkeji.com/api/app/lakala/merchant/file/upload"></wd-upload>
        </wd-cell>

        <wd-cell title="收银台照" title-width="100px">
          <wd-upload @success="(_event) => onSuccess(_event, 'CHECKSTAND_IMG')" :limit="1" :form-data="{
            sourcechnl: 1,
            imgType: 'CHECKSTAND_IMG',
          }" v-model:file-list="fileList6" accept="image"
            action="https://ryxkeji.com/api/app/lakala/merchant/file/upload"></wd-upload>
        </wd-cell>
      </wd-cell-group>
      <view class="footer mt24rpx">

        <wd-button type="primary" size="large" @click="hetong" block>签署合同</wd-button>
        <wd-button custom-class="mt-12rpx" type="primary" size="large" :loading="sumbitLoading" @click="handleSubmit"
          block>提交</wd-button>
      </view>
    </wd-form>
  </view>
</template>

<script lang="ts" setup>
import { useColPickerData } from '@/hooks/useColPickerData'
import { httpGet, httpPost } from '@/utils/http'
import { UploadFile, UploadMethod } from 'wot-design-uni/components/wd-upload/types'
const { colPickerData, findChildrenByCode } = useColPickerData()
import { areaList, bankAreaList } from './utils'
import { onUnmounted } from 'vue'
import dayjs from 'dayjs'

const sumbitLoading = ref(false)



/* 合同信息 */
const contractData = ref<any>();

const hetong = async () => {

  try {
    uni.showLoading({
      title: '获取合同信息...',
      mask: true,
    });
    const _bankInfo = bank.value.data

    const _Res = await httpPost('/api/app/lakala/merchant/contract/apply', {
      "larName": model.larName,
      "larIdCard": model.larIdCard,
      "contactMobile": model.contactMobile,
      "accountNo": model.accountNo,
      "openningBankCode": _bankInfo?.branchBankNo,
      "openningBankName": _bankInfo?.branchBankName,
    })

    uni.hideLoading()
    console.log('_Res', _Res);


    if (_Res?.resp_data?.result_url) {
      /* 跳转到合同页面 */
      // uni.navigateTo({
      //   url: '/pages/index/contractData/index?signUrl=' + _Res?.signUrl,
      // })
      uni.navigateTo({
        url: '/pages/index/contractData/index?signUrl=' + _Res?.resp_data?.result_url,
      })
    }
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: error.message,
      icon: 'error',
    })

  }

}


/* 获取当前用户是否有进件中 */
const getApplying = async () => {
  const _res = await httpPost('/api/app/lakala/merchant/isApplying')
  console.log('获取当前用户是否有进件中,', _res)

  contractData.value = _res;

  return _res
}



onShow(() => {
  console.log('显示了');
  getApplying()
})

// 获取地区数据
const getAreaData = async (code = 1) => {
  return await httpGet<any[]>(`/api/app/lakala/merchant/areaList?parentCode=${code}`)
}

/* 获取银行开户行 */
const getBankData = async (code = 1) => {
  return await httpGet<any[]>(`/api/app/lakala/merchant/bankList?parentCode=${code}`)
}

/* 获取银行对应的地区信息 */
const getBankAreaData = async (code = 1) => {
  return await httpGet<any[]>(`/api/app/lakala/merchant/bankAreaList?parentCode=${code}`)
}

// 提交进件
const submit = async (data) => {
  try {
    sumbitLoading.value = true;
    uni.showLoading({ title: '提交中...' })
    const _Res = await httpPost('/api/app/lakala/merchant/apply', data)


    

    if (_Res?.error?.error !== 200) {
      uni.showModal({
        title: '提示',
        content: _Res?.error?.message,
        showCancel: false,
      })
    }

    uni.showToast({
      title: '提交成功',
      icon: 'success',
    })

    // 返回上一页
    uni.navigateBack()

    console.log('进件结果', _Res)
    uni.hideLoading()
    sumbitLoading.value = false;
  } catch (error) {
    console.log('error', error);
    uni.hideLoading()
    sumbitLoading.value = false;
    uni.showToast({
      title: error.message,
      icon: 'error',
    })

  }
}

// 商户地址
const areaValue = ref<string[]>([])

/* 开户行 */
const openningBank = ref<any[]>([])

const area = ref<any[]>([
  areaList.map((item) => {
    return {
      value: item.value,
      label: item.text,
    }
  }),
])

/* 银行地区 */
const bankArea = ref<any[]>([
  bankAreaList.map((item) => {
    return {
      value: item.code,
      label: item.name,
      data: item,
    }
  }),
])

onMounted(async () => { })

const columnChange = async ({ selectedItem, resolve, finish }) => {
  try {
    const _list: any = await getAreaData(selectedItem?.value)

    if (_list && _list.length) {
      resolve(
        _list.map((item) => {
          return {
            value: item.code,
            label: item.name,
          }
        }),
      )
    } else {
      finish()
    }
  } catch (error) {
    finish()
  }
}

/* 银行列表 */
const bank = ref<any>([])

/* 银行省级地区信息 */
const settleProvinceInfo = ref<any>({})

/* 银行市级地区信息 */
const settleCityInfo = ref<any>({})

/* 选择银行开户地区回调 */
const handleOpenningBankColumnChange = async ({
  selectedItem,
  resolve,
  finish,
  index,
  rowIndex,
}) => {
  /* 判断是否点击到第二级，通过判断字符是否含有市或者州 */

  if (index === 0) {
    settleProvinceInfo.value = selectedItem.data
  } else if (index === 1) {
    settleCityInfo.value = selectedItem.data
  }

  console.log(' index,rowIndex', { index, rowIndex, selectedItem })
  try {
    if (index === 0) {
      const _list: any = await getBankAreaData(selectedItem?.value)
      if (_list && _list.length) {
        resolve(
          _list.map((item) => {
            return {
              value: item.code,
              label: item.name,
              data: item,
            }
          }),
        )
      } else {
        finish()
      }
    } else {
      const _rest: any = await getBankData(selectedItem?.value)

      console.log('_rest_rest_rest_rest', _rest)

      if (_rest && _rest.length) {
        resolve(
          _rest?.map((item) => {
            return {
              value: item.id,
              label: item.branchBankName,
              data: item,
            }
          }),
        )
      } else {
        bank.value = selectedItem
        finish()
      }
    }
  } catch (error) { }
}

function handleConfirm({ value }) {
  console.log(value)
  areaValue.value = value
}

/* 选择开户行回调 */
const handleOpenningBankConfirm = ({ value }) => {
  console.log(value)
  openningBank.value = value
}

// 身份证正面
const ID_CARD_FRONT_IMAGE = ref<any>({
  showUrl: '',
  url: '',
})

// 身份证反面
const ID_CARD_BEHIND_IMAGE = ref<any>({
  showUrl: '',
  url: '',
})

// 银行卡照片
const BANK_CARD_IMAGE = ref<any>({
  showUrl: '',
  url: '',
})

// 门头图
const SHOP_OUTSIDE_IMG = ref<any>({
  showUrl: '',
  url: '',
})

// 内设照
const SHOP_INSIDE_IMG = ref<any>({
  showUrl: '',
  url: '',
})

// 收银台照片
const CHECKSTAND_IMG = ref<any>({
  showUrl: '',
  url: '',
})

let fileList1 = ref<UploadFile[]>([])
let fileList2 = ref<UploadFile[]>([])
let fileList3 = ref<UploadFile[]>([])
let fileList4 = ref<UploadFile[]>([])
let fileList5 = ref<UploadFile[]>([])
let fileList6 = ref<UploadFile[]>([])

const lakalaToken = ref<any>('')

const onSuccess = (res: any, type: string) => {
  if (res?.file?.response) {
    const _iamgeRes = JSON.parse(res.file.response)
    console.log('_iamgeRes', _iamgeRes)

    // 如果是身份证正面
    if (type === 'ID_CARD_FRONT') {
      ID_CARD_FRONT_IMAGE.value = {
        showUrl: _iamgeRes.data.showUrl,
        url: _iamgeRes.data.url,
      }
    }
    // 如果是身份证反面
    else if (type === 'ID_CARD_BEHIND') {
      ID_CARD_BEHIND_IMAGE.value = {
        showUrl: _iamgeRes.data.showUrl,
        url: _iamgeRes.data.url,
      }
    }
    // 如果是银行卡
    else if (type === 'BANK_CARD') {
      BANK_CARD_IMAGE.value = {
        showUrl: _iamgeRes.data.showUrl,
        url: _iamgeRes.data.url,
      }
    }
    // 如果是门头
    else if (type === 'SHOP_OUTSIDE_IMG') {
      SHOP_OUTSIDE_IMG.value = {
        showUrl: _iamgeRes.data.showUrl,
        url: _iamgeRes.data.url,
      }
    }
    // 内设照
    else if (type === 'SHOP_INSIDE_IMG') {
      SHOP_INSIDE_IMG.value = {
        showUrl: _iamgeRes.data.showUrl,
        url: _iamgeRes.data.url,
      }
    }
    // 收银台
    else if (type === 'CHECKSTAND_IMG') {
      CHECKSTAND_IMG.value = {
        showUrl: _iamgeRes.data.showUrl,
        url: _iamgeRes.data.url,
      }
    }
  }
}

let model = reactive<any>({
  larIdCard: '',
  contactMobile: '',
  larIdCardStart: '',
  larIdCardEnd: '',
  merRegName: '',
  merName: '',
  email: '',
  accountNo: '',
  merAddr: '',
  larName: '',
})

onUnmounted(() => {
  console.log('销毁了');
  // 把model的值缓存到本地存储中
  uni.setStorageSync('APP_MER_INFO', model); 

  // 把身份证正面和反面都存本地
  // uni.setStorageSync('ID_CARD_FRONT_IMAGE', ID_CARD_FRONT_IMAGE.value);

})

onMounted(() => {
  const _default = uni.getStorageSync('APP_MER_INFO');

  console.log('_default_default_default', _default);


  // // 给model设置默认值
  // model = _default || model;

  setTimeout(() => {
    if (_default) {
      // 逐个属性更新，保持响应式
      Object.keys(_default).forEach(key => {
        console.log('_default[key]', {
          key,
          value: _default[key]
        });

        if (model.hasOwnProperty(key)) {
          model[key] = _default[key];
        }
      });
    }
  }, 500);

  // ID_CARD_FRONT_IMAGE.value = uni.getStorageSync('ID_CARD_FRONT_IMAGE');
})


const form = ref()

async function handleSubmit() {

  const _test = await getApplying();

  console.log('_test', _test);

  if (_test?.status != 1) {
    return uni.showToast({
      title: '请先完成签署合同',
      icon: 'none',
    })
  }



  // if (contractData.value.status != 1) {
  //   return uni.showToast({
  //     title: '请先完成签署合同',
  //     icon: 'none',
  //   })
  // }


  form.value
    .validate()
    .then(({ valid, errors }) => {
      console.log(valid, errors)
      if (valid) {
        console.log('formData', model)

        // 检查身份证，银行卡，门头，内设照是否正常上传
        if (!BANK_CARD_IMAGE.value.url) {
          return uni.showToast({
            title: '请上传银行卡',
            icon: 'none',
          })
        } else if (!ID_CARD_FRONT_IMAGE.value.url) {
          return uni.showToast({
            title: '请上传身份证正面',
            icon: 'none',
          })
        } else if (!ID_CARD_BEHIND_IMAGE.value.url) {
          return uni.showToast({
            title: '请上传身份证反面',
            icon: 'none',
          })
        } else if (!SHOP_OUTSIDE_IMG.value.url) {
          return uni.showToast({
            title: '请上传门头照',
            icon: 'none',
          })
        } else if (!SHOP_INSIDE_IMG.value.url) {
          return uni.showToast({
            title: '请上传店内照',
            icon: 'none',
          })
        } else if (!CHECKSTAND_IMG.value.url) {
          return uni.showToast({
            title: '请上传收银台',
            icon: 'none',
          })
        }

        /* 找到对应的银行信息 */
        const _bankInfo = bank.value.data

        const _obj = {
          ...model,
          provinceCode: areaValue.value[0],
          cityCode: areaValue.value[1],
          countyCode: areaValue.value[2],
          openningBankCode: _bankInfo?.branchBankNo,
          openningBankName: _bankInfo?.branchBankName,
          clearingBankCode: _bankInfo?.clearNo,

          settleProvinceCode: settleProvinceInfo.value.code,
          settleProvinceName: settleProvinceInfo.value.name,
          settleCityCode: settleCityInfo.value.code,
          settleCityName: settleCityInfo.value.name,
          // 身份证从毫秒级时间戳转成xxxx-xx-xx格式
          larIdCardStart: dayjs(model.larIdCardStart).format('YYYY-MM-DD'),
          larIdCardEnd: dayjs(model.larIdCardEnd).format('YYYY-MM-DD'),

          attchments: [
            // 银行卡照片
            {
              id: BANK_CARD_IMAGE.value.url,
              type: 'BANK_CARD',
              showUrl: BANK_CARD_IMAGE.value.showUrl,
            },
            // 身份证正面
            {
              id: ID_CARD_FRONT_IMAGE.value.url,
              type: 'ID_CARD_FRONT',
              showUrl: ID_CARD_FRONT_IMAGE.value.showUrl,
            },
            // 身份证反面
            {
              id: ID_CARD_BEHIND_IMAGE.value.url,
              type: 'ID_CARD_BEHIND',
              showUrl: ID_CARD_BEHIND_IMAGE.value.showUrl,
            },
            // 门头
            {
              id: SHOP_OUTSIDE_IMG.value.url,
              type: 'SHOP_OUTSIDE_IMG',
              showUrl: SHOP_OUTSIDE_IMG.value.showUrl,
            },
            // 内设照
            {
              id: SHOP_INSIDE_IMG.value.url,
              type: 'SHOP_INSIDE_IMG',
              showUrl: SHOP_INSIDE_IMG.value.showUrl,
            },
            // 收银台
            {
              id: CHECKSTAND_IMG.value.url,
              type: 'CHECKSTAND_IMG',
              showUrl: CHECKSTAND_IMG.value.showUrl,
            },
          ],
          ecNo: _test?.ecApplyId
        }

        submit(_obj)

        console.log('提交参数', _obj)
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}
</script>

<style lang="scss" scoped>
//
.text {
  margin-top: 12px;
}

.charts {
  width: 750rpx;
  height: 500rpx;

  margin-top: 30rpx;
}
</style>
